from enum import Enum
from typing import Optional

import uvicorn
from fastapi import FastAPI
from fastapi.openapi.docs import get_swagger_ui_html
from starlette.staticfiles import StaticFiles

# 创建 FastAPI 应用实例，并把默认的/docs请求禁用
# debug表示是否开启调试模式，默认是False
app = FastAPI(docs_url=None,debug=True)
app.mount("/static", StaticFiles(directory="../static"), name="static")    # 静态文件

@app.get("/docs", include_in_schema=False)
def custom_swagger_ui():
    return get_swagger_ui_html(
        openapi_url = "/openapi.json",
        title = "Swagger UI for FastAPI",
        swagger_js_url="/static/swagger-ui-bundle.min.js",
        swagger_css_url="/static/swagger-ui.min.css"
    )


# 查询参数：它只需要定义在路由处理函数中使用参数形式即可
@app.get("/users")
async def get_user(page_index:int,page_size:int):
    return {"page_index":page_index,"page_size":page_size}

# 带默认值参数的查询参数
@app.get("/students")
# Optional表示参数可以是None或指定的类型。在这里允许page_index和page_size参数在未提供时使用默认值，同时保持类型提示的准确性
async def get_student(page_index:int=1,page_size:Optional[int]=10):
    return {"page_index":page_index,"page_size":page_size}


# 这里继承str的目的是为了让枚举成员可以直接被序列化为字符串，便于在FastAPI中作为查询参数时正确解析和验证
class Gender(str,Enum):
    MALE = "male"
    FEMALE = "female"

# 路径参数与查询参数混合使用
@app.get("/users/{user_id}/friends")
async def get_user_friends(user_id:int,gender:Optional[Gender]='male'):
    return {"user_id":user_id,"gender": gender.value}

if __name__ == '__main__':
    uvicorn.run("main:app", host="127.0.0.1", port=8002, reload=True)